package com.scalar.chiptrack.sales.actions;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.sales.forms.AddressForm;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.EndUserDAO;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.util.MessageResources;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * Author: Prabhanjan
 * Date: Mar 20, 2004
 * Time: 8:42:40 PM
 */

public final class AddEndUserAddressAction extends ChipTrackAction
{

    private static final String ACTION_NAME = "/addEndUserAddress.do"; // Added by Basha (08/08/2003)

    // ----------------------------------------------------- Instance Variables


    // --------------------------------------------------------- Public Methods


    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     * Return an <code>ActionForward</code> instance describing where and how
     * control should be forwarded, or <code>null</code> if the response has
     * already been completed.
     *
     * @param mapping The ActionMapping used to select this instance
     * @param form The optional ActionForm bean for this request (if any)
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception Exception if business logic throws an exception
     */
    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response )
            throws Exception
    {

        // Extract attributes and parameters we will need
        AddressForm subform = ( AddressForm ) form;
        String action = request.getParameter ( "action" );

        //Get the session, to retrieve the values
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );
        // Added by Basha (08/08/2003)
        if ( user == null )
        {
            // Modified by Veeru on 4th Oct 2004
            //session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString () );
            //return ( mapping.findForward ( "login" ) );
            request.setAttribute ( "closeWindowAfterSessionExp", "true" );
            return (mapping.findForward("success"));
        }
        // Added by Basha (08/08/2003)

        // Validate the request parameters specified by the user
        ActionErrors errors = new ActionErrors ();
        HashMap errorsTemp = new HashMap ();

        if ( "AddEndUserShippingAddress".equals ( action ) )
        {
            //Open the popup window...
            return ( mapping.findForward ( "success" ) );
        }

        if ( "SaveEndUserShippingAddress".equals ( action ) )
        {
            DBTransaction dbTransaction = null;
            boolean success = false;

            try
            {
                // Start transaction
                dbTransaction = DBTransaction.getInstance ();
                dbTransaction.begin ();

                int endUserId = Integer.parseInt ( request.getParameter ( "endUserId" ) );

                //Insert the address details in the Address Table and get addressId
                int addressId = SalesOrderDAO.saveShippingAddress ( dbTransaction,
                                                                    subform.getAddress1 (),
                                                                    subform.getAddress2 (),
                                                                    subform.getAddress3 (),
                                                                    subform.getAddress4 (),
                                                                    subform.getCity (),
                                                                    subform.getState (),
                                                                    subform.getZipCode (),
                                                                    subform.getCountry (),
                                                                    subform.getPhoneNumber (),
                                                                    subform.getFaxNumber (),
                                                                    subform.getEmail (),
                                                                    subform.getContactPerson (),
                                                                    subform.getCellNumber (), subform.getTagName()); //Added by sarada on 26th Jan 2004 to show contact person in address details

                if( !( "".equals( subform.getContactPerson() ) ) && !( Constants.SALES_INTEGRATION_TYPE_GREAT_PLAINS.equals( ConfigManager.getSalesIntegrationType() ) ) )
                {
                    // Added by veeru on 5th April 2004 to insert the contact person details in address contact person table
                    CustomerDAO.insertContactPerson (dbTransaction, addressId, subform.getContactPerson(), subform.getPhoneNumber(),subform.getCellNumber(), subform.getFaxNumber() , subform.getEmail() , subform.getSalesAckMail()  , subform.getShipAlerts() , subform.getproformaInvoice() ,subform.getpackingSlip() , subform.getcommerInvoice() ,"", "Address", false, false);
                }

                //Insert the values in the customer shippingtable
                EndUserDAO.insertEndUserShippingTable(dbTransaction, endUserId, addressId);

                success = true;
                // System.out.println("Address while inserting new address = " + addressId);
                session.setAttribute ( "newShippingAddressId", Integer.toString ( addressId ) );
                ArrayList shippingContactPersons = new ArrayList();
                shippingContactPersons.add(subform.getContactPerson());
                session.setAttribute ("shippingAddressContactPersons",shippingContactPersons );//Added by Veeru on 3rd May 2004)

                //Added by rohan on July 28th 2003
                //This will add the newly added address to the shippingAddresses array list

                ArrayList shippingList = ( ArrayList ) session.getAttribute ( "shippingAddresses" );
                String addrStr = "";

                //Added by sarada on 26th Jan 2004 to show contact person in address details
                if ( ( subform.getContactPerson () != null ) && ( subform.getContactPerson ().trim ().length () != 0 ) )
                {

                    // addrStr=subform.getContactPerson();
                    shippingList.add ( new org.apache.struts.util.LabelValueBean (
                            subform.getContactPerson (), Integer.toString ( addressId ) ) );
                }

                if ( ( subform.getAddress1 () != null ) && ( subform.getAddress1 ().trim ().length () != 0 ) )
                {
                    shippingList.add ( new org.apache.struts.util.LabelValueBean (
                            subform.getAddress1 (), Integer.toString ( addressId ) ) );
                }
                if ( ( subform.getAddress2 () != null ) && ( subform.getAddress2 ().trim ().length () != 0 ) )
                {
                    shippingList.add ( new org.apache.struts.util.LabelValueBean (
                            subform.getAddress2 () + ",", Integer.toString ( addressId ) ) );
                }
                if ( ( subform.getAddress3 () != null ) && ( subform.getAddress3 ().trim ().length () != 0 ) )
                {
                    shippingList.add ( new org.apache.struts.util.LabelValueBean (
                            subform.getAddress3 (), Integer.toString ( addressId ) ) );
                }
                if ( ( subform.getAddress4 () != null ) && ( subform.getAddress4 ().trim ().length () != 0 ) )
                {
                    shippingList.add ( new org.apache.struts.util.LabelValueBean (
                            subform.getAddress4 () + ",", Integer.toString ( addressId ) ) );
                }

                if ( ( subform.getCity () != null ) && ( subform.getCity ().trim ().length () != 0 ) )
                {
                    shippingList.add ( new org.apache.struts.util.LabelValueBean (
                            subform.getCity (), Integer.toString ( addressId ) ) );
                }
                if ( ( subform.getState () != null ) && ( subform.getState ().trim ().length () != 0 ) )
                {
                    if ( addrStr.trim ().length () != 0 )
                        addrStr = addrStr + " ," + subform.getState ();
                    else
                        addrStr = subform.getState ();

                }
                if ( ( subform.getZipCode () != null ) && ( subform.getZipCode ().trim ().length () != 0 ) )
                {
                    if ( addrStr.trim ().length () != 0 )
                        addrStr = addrStr + " ," + subform.getZipCode ();
                    else
                        addrStr = subform.getZipCode ();
                }
                if ( ( subform.getCountry () != null ) && ( subform.getCountry ().trim ().length () != 0 ) )
                {
                    if ( addrStr.trim ().length () != 0 )
                        addrStr = addrStr + " ," + subform.getCountry ();
                    else
                        addrStr = subform.getCountry ();
                }

                if ( addrStr.trim ().length () != 0 )
                    shippingList.add ( new org.apache.struts.util.LabelValueBean ( addrStr, Integer.toString ( addressId ) ) );

                //Modified by Rohan on September 8th 2003 for displaying a line after each address in the list
                shippingList.add ( new org.apache.struts.util.LabelValueBean ( "    ", Integer.toString ( addressId ) ) );

                session.setAttribute ( "shippingAddresses", shippingList );
                //End of additiong by rohan on july 28th 2003
            }
            catch ( ScalarException se )
            {
                //This Label is added by Kumaraswamy on Oct 15th, 2004.
                String shippingMethodLabel = null;
                try
                {
                    shippingMethodLabel = MessageResources.getMessageResources ( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage ( "label.sales.salesOrder.ShippingMethod" );
                    if ( shippingMethodLabel == null )
                    {
                        shippingMethodLabel = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                    }
                }
                catch ( NullPointerException e )
                {
                    shippingMethodLabel    = Labels.DEFAULT_SHIPPING_METHOD_LABEL;
                }
                errorsTemp.put ( ERROR_INTERNAL_SERVER_ERROR, "Could not Save "+shippingMethodLabel+" Value." );
                //errorsTemp.put ( ERROR_INTERNAL_SERVER_ERROR, ERROR_IN_SAVING_SHIPPED_ORDER );
                errorsTemp.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
                session.setAttribute ( SessionKeys.ERROR_REPORT_SUBJECT, " Error: Could Not Save Shipping Details " );
                session.setAttribute ( SessionKeys.ERROR_REPORT, se );

            }
            finally
            {
                // Rollback or Commit the Transaction
                if ( success == true )
                    dbTransaction.commit ();
                else
                    dbTransaction.rollback ();

            }
            if ( !errorsTemp.isEmpty () )
            {
                request.setAttribute ( SessionKeys.ERROR_MESSAGES, errors );
            }

            return ( mapping.findForward ( "success" ) );

        }



        // Report any errors we have discovered back to the original form
        if ( !errors.empty () )
        {
            saveErrors ( request, errors );
            return ( new ActionForward ( mapping.getInput () ) );
        }


        //Please look at this return later(Where do we need this retrurned) ????
        return ( mapping.findForward ( "success" ) );

    }


}
